package com.sto.stoapp.activity.sales;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.entity.ProblemEntity;
import com.sto.stoapp.http.BaseMessage;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.BlueWeigthManager;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BlueReadThread;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

@SuppressLint("HandlerLeak")
public class SalesProblemPieceActivity extends StoListenerActivity {

	// private StoHhmEditText code;
	private StoHhmEditText cause;

	private DataBusinessEntity dataBusiness;
	private String busiType = HomeBroadAction.AVIATION_SCANNER_BROAD;

	private final int CAUSE_RESULT = 0xfe;
	// private List<EditText> edit = new ArrayList<EditText>();
	private String CauseCode = "";
	private String CauseName = "";

	private TextView weight;
	private float blueWeight = -1;
	private String billNo="";
	private BaseDialog filterDialog=null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_problem_piece);
		Bundle extras = getIntent().getExtras();
		busiType = extras.getString("busiType");
		this.setTitleBottom(R.string.problem_piece, busiType);
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		/*
		 * 添加航空扫描员-问题件
		 * 
		 * @修改人：mgf
		 */
		// 航空-扫描-留仓件
		if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM);
		} else {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_PROBLEM);
		}

		bluetoothConnect();
	}

	private void initWidget() {
		code = (StoHhmEditText) this
				.findViewById(R.id.problem_odd_numbers_text);
		cause = (StoHhmEditText) this.findViewById(R.id.cause_text);
		weight = (TextView) this.findViewById(R.id.enter_count);
		// edit.add(code);
		if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM);
		} else {
			addUploadTable(EnumTableNames.STATUS_TABLE_PROBLEM);
		}
	}

	/**
	 * 监听控件
	 */
	private void initListen() {
		cause.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
//				SelectCause();
			}
		});

		findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SelectCause();
			}
		});

		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				cause.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				if (code.getText().toString().length() == 0) {
					Helper.showSoundToast(SalesProblemPieceActivity.this,
							getString(R.string.code_empty), false);
				} else {
					onScanResults(code.getText().toString());
				}
			}
		});

		/*
		 * code.setEditScanListener(new EditScanListener() {
		 * 
		 * @Override public void onScan() { ScanOpen(); }
		 * 
		 * @Override public void offScan() { ScanOff(); } });
		 */

		/*
		 * code.setOnClickListener(new StoOnClickListener(this) {
		 * 
		 * @Override public void mHonClick(View v) {
		 * onScanResults(code.getText().toString()); } });
		 */
	}

	/**
	 * 选择原因
	 */
	private void SelectCause() {
		String user_widget = "";
		if (UnifiedStaticType.loginType.equals(BaseMessage.SALES_VERSION)
				|| UnifiedStaticType.loginType
						.equals(BaseMessage.SCANNER_VERSION)) {
			user_widget = "N";
		}

		if (UnifiedStaticType.loginType.equals(BaseMessage.CENTER_VERSION)
				|| UnifiedStaticType.loginType
						.equals(BaseMessage.AVIATION_A_VERSION)
				|| UnifiedStaticType.loginType
						.equals(BaseMessage.AVIATION_Y_VERSION)) {
			user_widget = "C";
		}
		try {
			ProblemEntity tableParcel = new ProblemEntity();
			if (cause.getText().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_CAUSE_INFO_ALL);
				tableParcel.setSelectField(new String[] { user_widget });
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_CAUSE_INFO_ONLY);
				tableParcel.setSelectField(new String[] {
						cause.getText().toString(), user_widget });
			}
			Intent intent = new Intent(SalesProblemPieceActivity.this,
					StoProblemSelectActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, CAUSE_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("SelectCause", e.getMessage());
		}
	}

	/**
	 * 扫描码判断
	 * 
	 * @param code
	 *            扫描码
	 * @return true/ok or false
	 */
	private boolean CheckScanCode(String code) {
		boolean ret = false;

		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code, EnumTableNames.STATUS_TABLE_PROBLEM);

		switch (status) {
		// 条码空
		case CODE_EMPTY:
			// Helper.showSoundToast(SalesProblemPieceActivity.this,
			// getString(R.string.code_empty), false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(SalesProblemPieceActivity.this,
					getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:

			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	/**
	 * 扫描数据处理
	 */
	@SuppressLint("NewApi")
	private void processScanData() {
		try {

			if (!weight.getText().toString().isEmpty() && blueWeight <= 0) {
				Helper.showSoundToast(this, getString(R.string.no_weight_data),
						false);
				return;
			}

			if (!code.getText().toString().isEmpty() && !CauseCode.equals("")
					&& CauseName.equals(cause.getText().toString())) {

				billNo=code.getText().toString();
				float maxWeight=StoFilePreference.getInstance(this).getBlueWeight();
				if(blueWeight>maxWeight){
					ScanOff();
					filterDialog=new BaseDialog(this);
					filterDialog.setTitles("重量限制为【" + maxWeight + "】\n当前重量为【" + blueWeight + "】\n请确认重量是否准确");
					filterDialog.show();
					filterDialog.getvCanncel().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							ScanOpen();
						}
					});
					filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							//Add by wj过滤单号
							boolean isFilter= BillFilterUtil.isFilter(billNo,SalesProblemPieceActivity.this);
							if(isFilter){
								showFilterDialog(billNo);
								return;
							}
							//End by wj
							if (addPieceRecord(billNo)) {
								addCodeNumber();
								setSaveData(true);
								Helper.showSoundAndVibrator(SalesProblemPieceActivity.this, true);
								addScanRecordInfo(billNo,weight.getText().toString());
								// ticketNumber.setText(String.valueOf(++count));
								code.setSelection(code.length());
							}
							// 提示插入数据失败
							else {
								Helper.showSoundToast(SalesProblemPieceActivity.this,
										getString(R.string.code_repeat), false);
							}

							ScanOpen();
						}
					});
				}else {
					//Add by wj过滤单号
					boolean isFilter= BillFilterUtil.isFilter(code.getText().toString().trim(),this);
					if(isFilter){
						showFilterDialog(billNo);
						return;
					}
					//End by wj

					if (addPieceRecord(billNo)) {
						this.addCodeNumber();
						setSaveData(true);
						Helper.showSoundAndVibrator(this, true);
						// SoundManager.getInstance(this).playSuccessSound();
						addScanRecordInfo(code.getText().toString());
						// ticketNumber.setText(String.valueOf(++count));
						code.setSelection(code.length());
					}
					// 提示插入数据失败
					else {
						Helper.showSoundToast(this,
								getString(R.string.code_repeat), false);
					}

					ScanOpen();
				}

			} else if (code.getText().toString().isEmpty()) {
				// 提示单号不能为空

			} else if (cause.getText().toString().isEmpty()) {
				// 原因不能为空
				SoundManager.getInstance(this).playFailureSound();
				Helper.showToast(SalesProblemPieceActivity.this, "原因不能为空");
				cause.requestFocus();
				cause.setText("");
			} else if (CauseCode.equals("")
					|| !CauseName.equals(cause.getText().toString())) {
				// 没有选择问题件原因
				SoundManager.getInstance(this).playFailureSound();
				Helper.showToast(SalesProblemPieceActivity.this, "请选择正确的问题件原因!");
				cause.requestFocus();
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	/**
	 * 数据保存
	 * 
	 * @return true/成功 or false/失败
	 */
	private boolean addPieceRecord(String billNo) {
		boolean ret;

		dataBusiness.setBar_code_number(billNo);

		dataBusiness.setCodeType(getExpType(billNo));
		// 原因
		dataBusiness.setReason_number(CauseCode);
		dataBusiness.setUser_defined5(cause.getText().toString());
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());
		// 蓝牙重量
		if (blueWeight > 0) {
			// 重量
			dataBusiness.setWeight(String.valueOf(blueWeight));
			blueWeight = -1;
		}
		// 航空-扫描-问题件
		if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			dataBusiness
					.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM
							.getOpCode());
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM);
		} else {
			// Th t=new Th(this, code.getText().toString());
			// t.start();
			dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_PROBLEM
					.getOpCode());
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_PROBLEM);
		}

		return ret;
	}

	/**
	 * 选择列表返回的结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CAUSE_RESULT && resultCode == RESULT_OK) {
			String Cause = data.getStringExtra("Name");
			CauseCode = data.getStringExtra("CauseCode");
			if (Cause != null) {
				cause.setText(Cause);
				CauseName = Cause;
				cause.setSelection(cause.length());
				code.requestFocus();
			}
		} else if (requestCode == CAUSE_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			CauseCode = "";
			CauseName = "";
			cause.setText("");
			Helper.showSoundToast(this, getString(R.string.undefined), false);
		} else {

		}

	}

	@Override
	public void onBackPressed() {
		// 确定退出吗?
		showNotice();
		/*
		 * // 确定退出吗? new AlertDialog.Builder(this) .setTitle(R.string.prompt)
		 * .setMessage(R.string.is_exit) .setPositiveButton(R.string.change, new
		 * DialogInterface.OnClickListener() {
		 * 
		 * @Override public void onClick(DialogInterface dialog, int which) {
		 * 
		 * finish(); } }) .setNegativeButton(R.string.cancel, new
		 * DialogInterface.OnClickListener() {
		 * 
		 * @Override public void onClick(DialogInterface dialog, int which) {
		 * dialog.dismiss(); } }).setCancelable(false).show();
		 */
		// super.onBackPressed();

	}

	@Override
	protected void onDestroy() {

		bluetoothHandler.removeMessages(BlueWeigthManager.UPDATE_BLUE_DATA);

		super.onDestroy();
	}

	@Override
	protected void handlerScanData(String scanData) {

		if(null!=filterDialog && filterDialog.isShowing()){
			return;
		}

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;
			code.setText("");
			code.setText(result);
			code.setSelection(code.length());

			if (CheckScanCode(result)) {
				processScanData();
			}
			code.setText("");
		} else {
			// SoundManager.getInstance(SalesProblemPieceActivity.this)
			// .playFailureSound();
			// Helper.showToast(SalesProblemPieceActivity.this,
			// "单号不能为空!");
		}

	}

	/**
	 * 蓝牙连接
	 *
	 * @author wxf
	 *
	 */
	private void bluetoothConnect() {
		mBTAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBTAdapter != null) {
			if (mBTAdapter.isEnabled()) {
				weight.setText(R.string.now_connect_blue);
				blueConnecting();
			} else {
				// weight.setText(R.string.blue_no_open);
			}
		} else {
			// promptDialog(getText(R.string.blue_not_available).toString());
		}
	}

	/**
	 * 蓝牙正式连接
	 */
	private void blueConnecting() {
		String macAddress = StoFilePreference.getInstance(this)
				.getBluetoothMacAddress();
		if (!macAddress.equals("")) {
			if (blueConnectThread != null) {
				blueConnectThread.cancelDialog();
				blueConnectThread.clearBlueDevices();
				blueConnectThread = null;
			}
			// weight.setEnabled(false);
			blueConnectThread = new BlueReadThread(this, bluetoothHandler,
					macAddress, false);
			blueConnectThread.start();
		} else {
			weight.setText(R.string.select_blue_scales);
		}
	}

	private Handler bluetoothHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Log.d("logdebug:", "msg.what:" + msg.what);
			if (msg.what == BlueWeigthManager.UPDATE_BLUE_DATA) {
				if (blueConnectThread != null) {
					blueConnectThread.cancelDialog();
				}
				if (msg.obj != null && !msg.obj.toString().equals("")) {
					String result = msg.obj.toString();
					Log.d("msg=", String.valueOf(result));
					// 表示连接蓝牙失败
					if (result.equals(BlueWeigthManager.CONNECT_FAIL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							if (blueConnCount < 3) {
								blueConnecting();
								blueConnCount++;
								weight.setText(getText(
										R.string.blue_connect_fail).toString()
										+ ",正在重连" + blueConnCount + "...");
							} else {
								blueConnCount = 0;
								weight.setText(getText(
										R.string.blue_connect_fail).toString()
										+ ",请到系统设置, 重新设置蓝牙!");
							}
						}
					}
					// 没有选择秤型号
					else if (result
							.equals(BlueWeigthManager.NO_SELECT_SCALE_MODEL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(getText(
									R.string.no_select_scales_model).toString()
									+ "请到系统设置,设置蓝牙!");

						}

					}
					// 读取数据失败
					else if (result.equals(BlueWeigthManager.READ_ERROR)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(R.string.get_data_error);
						}
					} else {
						// 显示重量
						blueWeight = parseFloat(result);
						weight.setText(result);
					}
				}
			}
		}

	};
}
